<?php

require_once 'FForm.class.php';

class FSearchForm extends FForm
{
    
    private $gridColumns;
    
    private $insertForm;
    
    private $editForm;
    
    private $maximized = true;
    
    private $storeFields;
    
    private $idName;
    
    private $isLookupFieldForm;
    
    const LABEL_CAMPO_PESQUISA = 'Termo para pesquisa';
    
    public function __construct($name = 'fsearchform')
    {
        if ( $name == 'fsearchform' )
        {
            $name .= '_' . rand();
        }
        parent::__construct($name);
    }
    
    public function generate($show = false)
    {
        if ( !$this->controller instanceof FController )
        {
            $controller = $this->instantiateController();                                    
        }
        else
        {
            $controller = $this->controller;
        }
        
        $controller instanceof FController;
        
        // Tabela
        if ( !$this->tableName )
        {
            $this->tableName = $controller->getTable();
        }
        
        if ( !$this->idName )
        {
            $idx = $controller->obterChavesPrimariasDaTabela($this->tableName);            
            // Se não houver chave primária na tabela, assume o primeiro campo.
            if ( !$idx )
            {
                $tableColumns = $controller->listarColunasDaTabela($this->tableName);
                $idx[0]['name'] = $tableColumns[0];
            }
            
            if ( count($idx) > 1 )
            {
                foreach ( $idx as $i )
                {
                    $this->idName[] = $i['name'];
                }
            }
            else
            {
                $this->idName = $idx[0]['name'];
            }
        }        

        // Campos
        if ( !$this->formFields )
        {
            $field = new FTextField('fldSearch_' . rand(), self::LABEL_CAMPO_PESQUISA, 300);
            $field->setOnKeyDown(13, "_onBtnApplyClick()", $this->getName());
            $field->setLabelWidth(150);
            
            $fields[] = $field->generate();
        }
        else
        {
            foreach( $this->formFields as $key => $field )
            {
                $fields[] = $field->generate();
            }
        }
        
        $fields = implode(',', $fields);
        
        // Store fields
        if ( !$this->storeFields )
        {
            $this->storeFields = $controller->listarColunasDaTabela($this->tableName);
            
            foreach ( $this->storeFields as $stField )
            {
                if ( $foreignKey = $controller->getForeignKey($stField) )
                {
                    $foreignController = new FDefaultController();
                    $foreignController->setTable($foreignKey['table_ref']);
                    $foreignDescription = $foreignController->getDescriptionColumn();
                    
                    $this->addStoreField($foreignKey['table_ref'] . '$' . $foreignDescription);
                }
            }
        }
        $storeFields = implode("','", $this->storeFields);
        
        // Grid Columns
        foreach( $this->gridColumns as $key => $column )
        {
            $columns[] = $column->generate();
        }
        
        if ( !$this->gridColumns )
        {
            if ( is_array($this->idName) )
            {
                foreach ( $this->idName as $idName )
                {
                    $column = new FGridColumn($idName, 0, FGridColumn::ALIGN_CENTER, true);
                    $columns[] = $column->generate();
                }
                
                foreach($this->storeFields as $gridName )
                {
                    if ( !in_array($gridName, $this->idName) )
                    {
                        $column = $this->createGridColumn($gridName);
                        $columns[] = $column->generate();
                    }
                }
            }
            else
            {
                foreach($this->storeFields as $gridName )
                {
                    $column = $this->createGridColumn($gridName);
                    $columns[] = $column->generate();
                }
            }
        }
        $columns = implode(",", $columns);
        
        // Bottom Bar
        $bbar = $this->showBottomBar ? 'true' : 'false';
        
        // Maximized
        $maximized = $this->maximized ? 'true' : 'false';
        
        // Lookup Field Form
        $lkpFieldForm = $this->isLookupFieldForm ? 'true' : 'false';
        
        if ( !$this->insertForm )
        {
            $this->insertForm = $this->editForm;
        }
        
        if ( $this->insertForm instanceof FForm )
        {
            $this->insertForm->generate();
        }
        
        if ( $this->editForm instanceof FForm )
        {
            $this->editForm->generate();
        }
        
        // Page size
        // TODO: OBTER TAMANHO_PAGINA_GRID DAS CONFIGURACOES
        $pageSize = TAMANHO_PAGINA_GRID;
        
        $extCode =
        "
                Ext.define('{$this->name}', {                
                    extend: 'FSearchForm',
                    title: '{$this->title}',
                    info: '{$this->info}',
                    formFields: [$fields],
                    showBBar: $bbar,
                    maximized: $maximized,
                    isLookupFieldForm: $lkpFieldForm,
                    width: {$this->width},
                    height: {$this->height},
                    className: '{$controller->getModel()}',
                    table: '{$this->tableName}',
        ";
                    
        if ( $this->insertForm )
        {
            $extCode .= "insertForm: '{$this->insertForm->getName()}', ";
        }
        
        if ( $this->editForm )
        {            
            $extCode .= "editForm: '{$this->editForm->getName()}', ";
        }
         
        $extCode .=
        "
                    pageSize: {$pageSize},
                    gridColumnsConfig: [{$columns}],
                    storeFields: ['$storeFields'], 
        ";
                    
        if ( is_array($this->idName) )
        {
            $idxName = implode(',', $this->idName);
            $extCode .= "
                        idxName: '{$idxName}'
                    });
            ";
        }
        else
        {
            $extCode .= "
                        idxName: '{$this->idName}'
                    });
            ";
        }
                    
        echo($extCode);
                    
        if ( $show )
        {
            echo $this->show();
        }
    }
    
    private function createGridColumn($column)
    {        
        $gridColumn = new FGridColumn();
        
        $controller = $this->controller;
        $controller instanceof FController;
        
        $info = $controller->obterInformacaoDaColuna($column);
        $info instanceof FColumnInfo;
        if ( !$info->getName() )
        {
            $columnArray = explode('$', $column);
            $columnTable = $columnArray[0];
            $columnName = $columnArray[1];
            
            $columnController = new FController();
            $columnController->setTable($columnTable);
            $info = $columnController->obterInformacaoDaColuna($columnName);
            
            $gridColumn->setText($info->getComment() ? $info->getComment() : $columnTable . '.' . $columnName);
        }
        else
        {
            $gridColumn->setText($info->getComment() ? $info->getComment() : $this->tableName . '.' . $column);
        }

        if ( $foreignKey = $controller->getForeignKey($column) )
        {
            $foreignController = new FDefaultController();
            $foreignController->setTable($foreignKey['table_ref']);
            $foreignDescription = $foreignController->getDescriptionColumn();
            $foreignDescriptionInfo = $foreignController->obterInformacaoDaColuna($foreignDescription);
            
            $gridColumn->setText($foreignDescriptionInfo->getComment() ? $foreignDescriptionInfo->getComment() : $foreignKey['table_ref'] . '.' . $foreignDescription);
            $gridColumn->setSize($foreignDescriptionInfo->getLength());
        }
        else
        {
            if ( $info->getType() == FController::TYPE_VARCHAR )
            {
                // Nothing
            }
            elseif ( $info->getType() == FController::TYPE_TEXT )
            {
                // Nothing
            }
            elseif ( $info->getType() == FController::TYPE_DATE )
            {
                $gridColumn->setAlign(FGridColumn::ALIGN_CENTER);
            }
            elseif ( $info->getType() == FController::TYPE_INT || $info->getType() == FController::TYPE_BIGINT )
            {
                $gridColumn->setAlign(FGridColumn::ALIGN_CENTER);
            }
            
            $gridColumn->setSize($info->getLength());
        }
        
        return $gridColumn;
    }
    
    public function getGridColumns() {
        return $this->gridColumns;
    }

    public function setGridColumns($gridColumns) {
        $this->gridColumns = $gridColumns;
    }
    
    public function addGridColumn($column) {
        $this->gridColumns[] = $column;
    }

    public function getMaximized() {
        return $this->maximized;
    }

    public function setMaximized($maximized) {
        $this->maximized = $maximized;
    }
    
    public function getStoreFields() {
        return $this->storeFields;
    }

    public function setStoreFields($storeFields) {
        $this->storeFields = $storeFields;
    }

    public function addStoreField($storeField) {
        $this->storeFields[] = $storeField;
    }
    
    public function getIdName() {
        return $this->idName;
    }

    public function setIdName($idName) {
        $this->idName = $idName;
    }
    
    public function getInsertForm() {
        return $this->insertForm;
    }

    public function setInsertForm($insertForm) {
        $this->insertForm = $insertForm;
    }
        
    public function getEditForm() {
        return $this->editForm;
    }

    public function setEditForm($editForm) {
        $this->editForm = $editForm;
    }
    
    public function getIsLookupFieldForm() {
        return $this->isLookupFieldForm;
    }

    public function setIsLookupFieldForm($isLookupFieldForm) {
        $this->isLookupFieldForm = $isLookupFieldForm;
    }
    
}

?>
